package adapters;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import models.Goods;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tie.catalogo.R;

public class CuadriculaAdapter extends BaseAdapter{
	
	ArrayList<Goods> goods;
	LayoutInflater inflater;
	Context context;
	SharedPreferences prefs;
	
	public CuadriculaAdapter(Context context, ArrayList<Goods> goods) {
		// TODO Auto-generated constructor stub
		this.goods = goods;
		prefs = context.getSharedPreferences("ajustes", 0);
		this.context = context;
		inflater = LayoutInflater.from(context);
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return goods.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		arg1 = inflater.inflate(R.layout.grid_cuadricula, null);
		TextView texto = (TextView)arg1.findViewById(R.id.texto);
		ImageView img = (ImageView)arg1.findViewById(R.id.imagen);
		texto.setText(goods.get(arg0).getNAME());
		//Cargar la imagen y ponerla en la lista

		 //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        try {
			BitmapFactory.decodeStream(new FileInputStream(Environment.getExternalStorageDirectory()+"/catalog/images/"+goods.get(arg0).getURL()),null,o);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        //The new size we want to scale to
        final int REQUIRED_SIZE=prefs.getInt("imgSize", 70);

        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
            scale*=2;

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
		try {
			img.setImageBitmap(BitmapFactory.decodeStream(new FileInputStream(Environment.getExternalStorageDirectory()+"/catalog/images/"+goods.get(arg0).getURL()), null, o2));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Cargar la imagen y ponerla en la lista END//
		return arg1;
	}

}
